<?php
/**
 * Created by PhpStorm.
 * Script Name: Mp.php
 * Create: 2022/12/22 17:52
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\service;
use app\common\service\Media;
use app\common\service\Tenant as TenantService;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Article;
use plugin\wechat\app\model\Mp as MpM;
use plugin\wechat\app\model\MpMenu as MpMenuM;
use plugin\wechat\app\model\MpFollow;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use think\facade\Db;
use Support\Request;

class Mp extends Common
{
    const EVENT_SUBSCRIBE = 'subscribe';
    const EVENT_UNSUBSCRIBE = 'unsubscribe';
    const EVENT_LOCATION = 'event_location';
    const EVENT_VIEW = 'view';
    const EVENT_CLICK = 'click';
    const EVENT_SCAN = 'scan';
    const EVENT_CARD = 'card';

    const MSG_TEXT = 'text';
    const MSG_IMAGE = 'image';
    const MSG_VOICE = 'voice';
    const MSG_VIDEO = 'video';
    const MSG_SHORTVIDEO = 'shortvideo';
    const MSG_LOCATION= 'location';
    const MSG_LINK = 'link';
    const DEFAULT_ANS = 'default';

    const ADD_SCENE_SEARCH = 'ADD_SCENE_SEARCH'; //公众号搜索，
    const ADD_SCENE_ACCOUNT_MIGRATION = 'ADD_SCENE_ACCOUNT_MIGRATION';//公众号迁移  ，
    const ADD_SCENE_PROFILE_CARD='ADD_SCENE_PROFILE_CARD';// 名片分享，
    const ADD_SCENE_QR_CODE = 'ADD_SCENE_QR_CODE';// 扫描二维码，
    const ADD_SCENE_PROFILE_LINK = 'ADD_SCENE_PROFILE_LINK';  //图文页内名称点击，
    const ADD_SCENE_PROFILE_ITEM = 'ADD_SCENE_PROFILE_ITEM'; // 图文页右上角菜单，
    const ADD_SCENE_PAID = 'ADD_SCENE_PAID'; // 支付后关注，
    const ADD_SCENE_WECHAT_ADVERTISEMENT = 'ADD_SCENE_WECHAT_ADVERTISEMENT'; // 微信广告，
    const ADD_SCENE_REPRINT = 'ADD_SCENE_REPRINT'; // 他人转载 ,
    const ADD_SCENE_LIVESTREAM ='ADD_SCENE_LIVESTREAM'; //视频号直播，
    const ADD_SCENE_CHANNELS = 'ADD_SCENE_CHANNELS'; // 视频号 ,
    const ADD_SCENE_OTHERS = 'ADD_SCENE_OTHERS'; // 其他

    /**
     * 关注来源
     * @param null $id
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function subscribeScenes($id = null){
        $list = [
            self::ADD_SCENE_SEARCH => '公众号搜索',
            self::ADD_SCENE_ACCOUNT_MIGRATION=> '公众号迁移',
            self::ADD_SCENE_PROFILE_CARD => '名片分享',
            self::ADD_SCENE_QR_CODE=> '扫描二维码',
            self::ADD_SCENE_PROFILE_LINK => '图文页内名称点击',
            self::ADD_SCENE_PROFILE_ITEM => '图文页右上角菜单',
            self::ADD_SCENE_PAID => '支付后关注',
            self::ADD_SCENE_WECHAT_ADVERTISEMENT=> '微信广告',
            self::ADD_SCENE_REPRINT => '他人转载',
            self::ADD_SCENE_LIVESTREAM => '视频号直播',
            self::ADD_SCENE_CHANNELS => '视频号',
            self::ADD_SCENE_OTHERS=> '其他',
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 获取模版消息
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function templateMessagePull($mp_info = null){
        $request = request();
        is_null($mp_info) && $mp_info = $request->mpInfo;
        $app = self::getApp($mp_info);
        $res = $app->template_message->getPrivateTemplates();
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 生成短网址
     * @param string $url
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function urlShorten($url = '', $mp_info = null){
        $request = request();
        is_null($mp_info) && $mp_info = $request->mpInfo;
        $app = self::getApp($mp_info);
        $res = $app->url->shorten($url);
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 根据ticket获取二维码地址
     * @param $ticket
     * @param null $mp_info
     * @return string
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function qrcodeGet($ticket, $mp_info = null){
        $request = request();
        is_null($mp_info) && $mp_info = $request->mpInfo;
        $app = self::getApp($mp_info);
        return $app->qrcode->url($ticket);
    }

    /**
     * 生成带参二维码
     * @param string $scene_str
     * @param int $expire
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function qrcodeCreate($scene_str = '', $expire = 0, $mp_info = null){
        $request = request();
        is_null($mp_info) && $mp_info = $request->mpInfo;
        $app = self::getApp($mp_info);
        if($expire){
            $res = $app->qrcode->temporary($scene_str, $expire);
        }else{
            $res = $app->qrcode->forever($scene_str);
        }
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 发送客服消息
     * @param $message
     * @param $to
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function customerServiceMessageSend($message, $to, $mp_info = null){
        $request = request();
        is_null($mp_info) && $mp_info = $request->mpInfo;
        $app = self::getApp($mp_info);
        $res = $app->customer_service->message($message)->to($to)->send();
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 特殊消息或事件
     * @param null $id
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function specialEvents($id = null){
        $list = [
            self::EVENT_SUBSCRIBE => '关注事件',
            self::EVENT_UNSUBSCRIBE => '取关事件',
            self::MSG_IMAGE => '图片消息',
            self::MSG_VOICE => '语音消息',
            self::MSG_VIDEO => '视频消息',
            self::MSG_SHORTVIDEO => '短视频消息',
            self::MSG_LOCATION => '地理位置消息',
            self::MSG_LINK => "链接消息",
            self::EVENT_LOCATION => '上报地理位置事件',
            self::EVENT_CARD => '卡券事件',
            self::DEFAULT_ANS => '默认回复'
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 获取粉丝信息
     * @param string $openid
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function userGet($openid = '', $mp_info = null){
        $app = self::getApp($mp_info);
        $response = $app->user->get($openid);
        if(!empty($response['errcode'])){
            return $response['errmsg'];
        }
        return $response;
    }

    /**
     * 回复类型
     * @param null $id
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function replyTypes($id = null){
        $list = [
            Media::TEXT => '文本',
            Media::IMAGE => '图片',
            Media::LINK => '链接',
            Media::VOICE => '语音',
            Media::MUSIC => '音乐',
            Media::VIDEO => '视频',
            Media::APP => '应用'
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 清空接口调用
     * @param string $appid
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function quotaClear(){
        $app = self::getApp();
        $res = $app->base->clearQuota();
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 接口调用查询
     * @param string $path
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function quotaGet($path = ''){
        $app = self::getApp();
        $res = $app->base->getQuota($path);
        if(!empty($res['errcode'])){
            return OpenPlatformService::errors($res['errcode'], $res['errmsg']);
        }
        return $res;
    }

    /**
     * 临时素材获取
     * @param array $params
     * @return bool|string
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    static function mediaGet($params = []){
        $media_id = $params['media_id'];
        $app = self::getApp();
        return $app->media->get($media_id);
    }

    /**
     * 永久素材获取
     * @param array $params
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function materialGet($params = []){
        $media_id = $params['media_id'];
        $app = self::getApp();
        $res = $app->material->get($media_id);
        if(!empty($res['errcode'])){
            return '获取素材失败,错误码:'.$res['errcode'].'，错误说明：' . $res['errmsg'];
        }
        return true;
    }

    /**
     * 素材删除
     * @param array $params
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function materialDel($params = []){
        $media_id = $params['media_id'];
        $app = self::getApp();
        $res = $app->material->delete($media_id);
        if(!empty($res['errcode'])){
            return '删除素材失败,错误码:'.$res['errcode'].'，错误说明：' . $res['errmsg'];
        }
        return true;
    }

    /**
     * 上传素材到微信服务器
     * @param array $params
     * @return array|bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function materialUpload($params = []){
        $media_type = $params['type'];
        if(!in_array($media_type, [Media::IMAGE, Media::VOICE, Media::VIDEO, Media::NEWS])){
            return  true;
        }
        $app = self::getApp();
        $path = $media_type != Media::NEWS ? $params['path'] : '';

        switch ($media_type){
            case Media::NEWS: //图文
                $news_list = $params['news_list'];
                $list = [];
                foreach ($news_list as $news){
                    $list[] = new Article($news);
                }
                if(empty($params['update'])){
                    $res = $app->material->uploadArticle($list);
                }else{
                    $res = $app->material->updateArticle($params['media_id'], $list);
                }
                break;
            case Media::VOICE:
                $res = $app->material->uploadVoice($path);
                break;
            case Media::VIDEO:
                $res = $app->material->uploadVideo($path, $params['title'], $params['desc']);
                break;
            default:
                $res = $app->material->uploadImage($path);
                break;
        }

        if(!empty($res['errcode'])){
            return '上传素材至公众号失败,错误码:'.$res['errcode'].'，错误说明：' . $res['errmsg'];
        }else{
            return ['media_id' => $res['media_id'], 'url' => empty($res['url']) ? "" : $res['url']];
        }
    }

    /**
     * 拉取永久素材
     * @param string $type
     * @param int $offset
     * @param int $count
     * @param null $mp_info
     * @return array|\EasyWeChat\Kernel\Support\Collection|mixed|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function materialList($type = 'image', $offset = 0, $count = 20, $mp_info = null){
        $request = request();
        if(!$mp_info){
            $mp_info = $request->mpInfo;
        }
        $app = self::getApp($mp_info, $request);
        $res = $app->material->list($type, $offset, $count);
        if(!empty($res['errcode'])){
            return $res['errmsg'];
        }
        return $res;
    }

    /**
     * 素材类型
     * @return array
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function materialTypes(){
        return [
            Media::TEXT => '文本',
            Media::IMAGE => '图片',
            //Media::NEWS => '图文',
            Media::VOICE => '音频',
            Media::VIDEO => '视频',
            Media::LINK => '链接',
            Media::MUSIC => '音乐',
        ];
    }

    /**
     * 发布自定义菜单
     * @param array $mp_info
     * @param array $menus
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function createMenus($mp_info = [], $menus = [])
    {
        $app = self::getApp($mp_info);
        $res = $app->menu->create($menus);
        if(!empty($res['errcode'])){
            return $res['errmsg'];
        }
        return true;
    }

    /**
     * 菜单类型
     * @param null $id
     * @return array|mixed
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public static function menuTypes($id = null){
        $list = [
            'click' => '触发关键词',
            'view' => '跳转URL',
            'miniprogram' => '跳转小程序',
            /*'scancode_push' => '扫码推事件',
            'scancode_waitmsg' => '扫码推事件且弹出“消息接收中”提示框',
            'pic_sysphoto' => '弹出系统拍照发图',
            'pic_photo_or_album' => '弹出拍照或者相册发图',
            'pic_weixin' => '弹出微信相册发图器',
            'location_select' => '弹出地理位置选择器',
            'media_id' => '下发永久素材', //图片、音频、视频、图文
            'view_limited' => '跳转图文消息URL' //其实可以是view的一种形式*/
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 拉取自定义菜单
     * button: [
     *      {
    "type": "text",
    "name": "text",
    "value": "This is text!"
    },
     *      {
    "name": "button",
    "sub_button": {
    "list": [
    {
    "type": "view",
    "name": "view_url",
    "url": "http://www.qq.com"
    },
     *          ]
     *      }
     * ]
     * @param array $mp_info
     * @return bool|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function pullMenus($mp_info = []){
        $app = self::getApp($mp_info);
        $mp_menu = $app->menu->current();
        $company_id = TenantService::getCompanyId();
        Db::startTrans();
        try {
            if(isset($mp_menu['selfmenu_info']['button']) && count($mp_menu['selfmenu_info']['button'])){
                $button_list = $mp_menu['selfmenu_info']['button'];
                $insert_data = [];
                foreach ($button_list as $k1 => $top_button){
                    $top_button['mp_id'] = $mp_info['id'];
                    $top_button['sort'] = $k1;
                    $top_button['company_id'] = $company_id;
                    if(isset($top_button['sub_button']['list']) && count($top_button['sub_button']['list'])){
                        $new = MpMenuM::create([
                            'sort' => $k1,
                            'company_id' => $company_id,
                            'mp_id' => $mp_info['id'],
                            'name' => $top_button['name']
                        ]);
                        foreach ($top_button['sub_button']['list'] as $k2 => $v){
                            $v['sort'] = $k2;
                            $v['pid'] = $new['id'];
                            $v['company_id'] = $company_id;
                            $v['mp_id'] = $mp_info['id'];
                            array_push($insert_data, $v);
                            MpMenuM::create($v);
                        }
                    }else{
                        array_push($insert_data, $top_button);
                        MpMenuM::create($top_button);
                    }
                }
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            dao_log()->error($e->getMessage());
            Db::rollback();
            return $e->getMessage();
        }
    }

    /**
     * @param array $mp_info
     * @param Request $request
     * @return \EasyWeChat\OfficialAccount\Application|\EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static function getApp($mp_info = [], Request $request = null){
        is_null($request) && $request = \request();
        empty($mp_info) && $mp_info = $request->mpInfo;
        $config = [
            'app_id'   => '',
            'secret'   => '',
            'token'    => '',
            'response_type' => 'array',

            'log' => [
                'default' => getenv('APP_DEBUG') ? 'dev' : 'prod' , // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => runtime_path() . '/logs/wechat/'.$mp_info['appid'].'.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => runtime_path() . '/logs/wechat/'.$mp_info['appid'].'.log',
                        'level' => 'error',
                        'days' => 3
                    ],
                ],
            ],

            'http' => [
                'timeout' => 0,
                'connect_timeout' => 0
            ]
        ];
        //var_dump($config['log']);
        if($mp_info['appsecret']){
            $config['aes_key'] = $mp_info['encodingaeskey'];
            $config['app_id'] = $mp_info['appid'];
            $config['secret'] = $mp_info['appsecret'];
            $config['token'] = $mp_info['refresh_token'];
            $app = Factory::officialAccount($config);
        }else{
            $app = OpenPlatformService::getOpenPlatform()->officialAccount($mp_info['appid'], $mp_info['refresh_token']);
        }
        //rebind cache driver
        $app->rebind('cache', new RedisAdapter(self::deserveRedis()));

        if($request){
            $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
            $symfony_request->headers = new HeaderBag($request->header());
            $app->rebind('request', $symfony_request);
        }
        return $app;
    }

    /**
     * 获取公众号信息
     * @param string|int $appid
     * @return array|mixed|\think\db\Query|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function getInfo($appid){
        return is_int($appid) ? MpM::find($appid)
            : MpM::where('appid', $appid)->find();
    }

    /**
     * 返回公众号的认证类型
     * @param array $mp
     * @return string
     * @author: fudaoji<fdj@kuryun.cn>
     */
    static function getTypeDesc($mp = []){
        return (
            ($mp['verify_type_info'] == -1 ? '未认证' : '认证') .
            ($mp['service_type_info'] < 2 ? '订阅号' : '服务号')
        );
    }

    /**
     * 授权方公众号类型
     * @param null $id
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function serviceTypes($id = null){
        $list = [
            0 => '订阅号',
            1 => '历史老帐号升级后的订阅号',
            2 => '服务号',
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 认证类型
     * @param null $id
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function verifyTypes($id = null){
        $list = [
            -1 => '未认证',
            0 => '微信认证',
            1 => '新浪微博认证',
            2 => '腾讯微博认证',
            3 => '已资质认证通过但还未通过名称认证',
            4 => '已资质认证通过、还未通过名称认证，但通过了新浪微博认证',
            5 => '已资质认证通过、还未通过名称认证，但通过了腾讯微博认证'
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 授权方微信公众号信息入库
     * @param array $auth_info
     * @param int $company_id
     * @param int $tenant_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author fudaoji<fdj@kuryun.cn>
     */
    static function updateAuthInfo($auth_info, $company_id = 0, $tenant_id = 0) {
        $result = false;
        $authorizer_info = $auth_info['authorizer_info'];
        $insert_data = [
            'appid'             => $auth_info['authorization_info']['authorizer_appid'],
            'appsecret'         => '', //区分手动接入
            'refresh_token'     => $auth_info['authorization_info']['authorizer_refresh_token'],
            'head_img' => $authorizer_info['head_img'] ?? '',
            'nick_name'         => $authorizer_info['nick_name'],
            'service_type_info' => $authorizer_info['service_type_info']['id'],
            'verify_type_info'  => $authorizer_info['verify_type_info']['id'],
            'user_name'         => $authorizer_info['user_name'],
            'principal_name'    => $authorizer_info['principal_name'],
            'alias'             => $authorizer_info['alias'],
            'business_info'     => json_encode($authorizer_info['business_info']),
            'qrcode_url'        => $authorizer_info['qrcode_url'],
            'idc'               => $authorizer_info['idc'],
            'signature'         => $authorizer_info['signature'],
            'func_info'         => json_encode($auth_info['authorization_info']['func_info']),
            'is_auth'           => 1,
            'account_status' => $authorizer_info['account_status'] ?? 1
        ];

        if($mp = self::getInfo($insert_data['appid'])) {
            $insert_data['id'] = $mp['id'];
            $result = MpM::update($insert_data);
        }elseif($company_id > 0 || in_array($insert_data['appid'], OpenPlatform::testApps())) { //兼容开放平台测试号
            $insert_data['company_id'] = $company_id;
            $insert_data['tenant_id'] = $tenant_id;
            $result = MpM::create($insert_data);
        }
        return $result;
    }

    /**
     * 公众号取消授权后
     * @param $mp
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function cancelAuth($mp)
    {
        MpM::update(['id' => $mp['id'], 'is_auth' => 0]);
    }

    /**
     * 获取当前mp
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getSessionInfo(){
        return session(CURRENT_MP);
    }

    /**
     * 设置当前mp
     * @param $data
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function setSessionInfo($data){
        return session([CURRENT_MP => $data]);
    }
}